﻿using Host;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonComponent
{
    public class CallDescriptionUDPHelper : IComponents
    {
        public override void OnEnterEnd()
        {
            base.OnEnterEnd();

            var udpservercomponents = GetSameGropComponents<UDPServerComponents>("UDPServerComponents");
            TAssert.Assert(udpservercomponents != null, "CM2CDCHttpHelper Rely UDPServerComponents");

            var calldescriptioncomponents = GetSameGropComponents<CallDescriptionComponents>("CallDescriptionComponents");
            TAssert.Assert(calldescriptioncomponents != null, "CM2CDCHttpHelper Rely CallDescriptionComponents");

            foreach (var item in calldescriptioncomponents.GetAllCallInfo())
            {
                Console.WriteLine("Start UDP Server Name " + item.Key);

                udpservercomponents.RouteData.RegisterRouteData(item.Key, (context) =>
                {
                    var headers = udpservercomponents.GetUDPHeaders(context);
                    var body = udpservercomponents.GetUDPBody(context);

                    Dictionary<string, object> query_map = new Dictionary<string, object>();
                    LitJson.JsonData json_data = LitJson.JsonMapper.ToObject(body);
                    foreach (string json_key in json_data.Keys)
                    {
                        var item_data = json_data[json_key];

                        if (item_data.IsString)
                            query_map.Add(json_key, item_data.ToString());
                    }

                    object obj = item.Value(query_map);

                    if (obj == null)
                        return null;

                    if (obj is string)
                        return Encoding.UTF8.GetBytes(obj as string);

                    return Encoding.UTF8.GetBytes(LitJson.JsonMapper.ToJson(obj));
                });
            }

            //udpservercomponents.RouteData.RegisterRouteData("", (context) =>
            //{
            //    string html_string = "";

            //    html_string += "<!DOCTYPE html>";
            //    html_string += "<html>";
            //    html_string += "<head>";
            //    html_string += "	<title>The Host Project</title>";
            //    html_string += "</head>";
            //    html_string += "<body>";
            //    html_string += "<ul>";
            //    foreach (var item in calldescriptioncomponents.GetAllCallInfo())
            //    {
            //        html_string += "	<li><a href=\"" + item.Key + "\">" + item.Key + "</a></li>";
            //    }
            //    html_string += "</ul>";
            //    html_string += "</body>";
            //    html_string += "</html>";

            //    return html_string;
            //});
        }
    }
}
